﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using EnetaMvc.ApplicationServices.Dto;
using EnetaMvc.ApplicationServices.SlaLogsDataExporter;
using EnetaMvc.Infrastructure;

namespace EnetaMvc.ApplicationServices
{
    public class FileService : IFileService
    {
        private string _defaultAvatarFile;

        private readonly IFileClient _fileClient;

        public FileService(IFileClient fileClient)
        {
            _fileClient = fileClient;
            _defaultAvatarFile = _fileClient.GetFileUri("profilepics", "avatar-user.gif");
        }

        public void SaveProfileImage(long userId, byte[] imageBytes)
        {           
            var imageSizes = new int[] { 32, 48, 64 };

            _fileClient.SaveFile("profilepics", userId.ToString(), imageBytes);

            foreach (var imageSize in imageSizes)
            {
                var fileName = string.Format("{0}_{1}x{1}.png", userId, imageSize);

                using (var memoryStream = new MemoryStream(imageBytes))
                using (var stream = new MemoryStream())
                {
                    ResizeImage(imageSize, memoryStream, stream);
                    _fileClient.SaveFile("profilepics", fileName, stream.ToArray());
                }
            }
        }

        public string GetProfileImageUrl(long userId, int size)
        {
            return GetProfileImageUrl(userId, size, true);
        }

        public string GetProfileImageUrl(long userId, int size, bool defaultIfNotExists)
        {
            if (userId <= 0)
                return _defaultAvatarFile;

            var fileName = string.Format("{0}_{1}x{1}.png", userId, size);

            if (!_fileClient.FileExists("profilepics", fileName))
                return _defaultAvatarFile;

            return _fileClient.GetFileUri("profilepics", fileName);
        }

        private static void ResizeImage(int sideLength, Stream fromStream, Stream toStream)
        {
            if (fromStream.Length == 0)
                return;

            using (var image = Image.FromStream(fromStream))
            using (var thumbnailBitmap = new Bitmap(sideLength, sideLength))
            {
                var a = Math.Min(image.Width, image.Height);
                var x = (image.Width - a) / 2;
                var y = (image.Height - a) / 2;

                using (var thumbnailGraph = Graphics.FromImage(thumbnailBitmap))
                {
                    thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                    thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
                    thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    var imageRectangle = new Rectangle(0, 0, sideLength, sideLength);
                    thumbnailGraph.DrawImage(image, imageRectangle, x, y, a, a, GraphicsUnit.Pixel);
                    thumbnailBitmap.Save(toStream, ImageFormat.Png);
                }
            }
        }

        public bool IsValidImage(byte[] imageBytes)
        {
            try
            {
                using (var mem = new MemoryStream())
                {
                    mem.Write(imageBytes, 0, imageBytes.Length);
                    var bmp = Image.FromStream(mem);
                    bmp.Dispose();
                }

                return true;
            }
            catch
            {
                return false;
            }
        }


        public void ExportSlaLogsToExcel(List<SlaMonitoringLogDto> slaLogs, string filepath)
        {
            SlaLogsExcelExporter exporter = new SlaLogsExcelExporter();
            using (var sw = new FileStream(filepath, FileMode.Create))
            {
                exporter.Export(sw, "xlsx", slaLogs);
            }
        }


        //public string SaveEditorImageToBlob(Stream imageStream, string contentType)
        //{
        //    var blobStorage = _storageAccount.CreateCloudBlobClient();
        //    CloudBlobContainer container = blobStorage.GetContainerReference("images");
        //    if (container.CreateIfNotExist())
        //    {
        //        // configure container for public access
        //        var permissions = container.GetPermissions();
        //        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
        //        container.SetPermissions(permissions);
        //    }

        //    string filename = "tinymce_" + Guid.NewGuid().ToString() + ".png";
        //    string uniqueBlobName = string.Format("images/{0}", filename);
        //    CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
        //    blob.Properties.ContentType = contentType;
        //    blob.UploadFromStream(imageStream);

        //    return blob.Uri.ToString();
        //}
    }
}
